import {action, observable, computed} from 'mobx';
import {message} from 'antd';
import * as API from "../../apis/performance/programViewApi";
import {programAuditOperationApi} from "../../apis/performance/programAuditListApi";
import {idsAndNamesToArr} from '../../util/Util'
import {WeaLocaleProvider} from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

/**
 * 绩效-考核方案
 * jiansong 2019/6/11
 */
export default class ProgramViewStore {

    @observable msg = "";//返回错误信息
    @observable loading = true; //加载中
    @observable hasRight = true; //是否有访问权限
    @observable hasCycle = true; //是否开启了考核周期
    @observable showDialog = false; //是否显示引用指标方案dialog
    @observable showItemDialog = false; //是否显示指标方案dialog
    @observable quoteProgram = true; //引用方案（false为引用指标）
    @observable data = []; //表格数据
    @observable isChangeStartdate = false; //是否更改了生效日期
    @observable total = 0; //数据数量
    @observable addStatus = false; //是否是新建状态
    @observable backSetting = false; //是否后台设置
    @observable logList = [];//日志列表
    @observable otherProgram = [];//其他方案
    @observable logTotal = 0;//日志总数
    @observable logCurrent = 1;//日志当前页数
    @observable pageSize = 5;//日志每页显示数量
    @observable backProgram = false;//是否后台返回的方案
    @observable auditidsManager = false;//审批人是否包含上级的上级

    @computed get logLastCount() { //计算日志未加载数量
        return this.logTotal - this.logCurrent * this.pageSize;
    }

    @computed get quoteTitle() { //引用框标题
        return this.quoteProgram ? getLabel(508694, '引用方案') : getLabel(509209, '引用方案指标');
    }

    @computed get showStatus() { //展示状态还是编辑状态
        if (this.backSetting) {
            return true;
        }
        if (this.backProgram && !this.addStatus) {
            return false;
        }
        let flag = this.detail.canedit;
        flag = this.detail.canAdd ? this.detail.canAdd : flag;
        if (this.detail.programstatus == 1) {
            flag = false;
        }
        if (this.addStatus) {
            flag = true;
        }
        return flag;
    }

    @computed get canAdd() { //是否能新建
        let flag = this.detail.canedit;
        flag = this.detail.canAdd ? this.detail.canAdd : flag;
        if (this.form.programid == '') {
            flag = false;
        }
        return flag;
    }

    @computed get auditidsData() { //审核人数据
        if (this.form.auditids == '-1') {
            if (this.backSetting) {
                return idsAndNamesToArr("-1", this.form.auditnames);
            } else {
                return idsAndNamesToArr(this.detail.managerid2, this.form.auditnames);
            }
        } else {
            return idsAndNamesToArr(this.form.auditids, this.form.auditnames);
        }
    }

    @computed get showNoticeMessage() { //是否显示生效日期提示
        if (this.backProgram) {
            return false;
        }
        if (this.isChangeStartdate) {
            if (this.form.startdate > this.detail.noticeDate) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    @observable typeOption = [
        {key: "", showname: ""},
        {key: "1", showname: getLabel('19398', '月度')},
        {key: "2", showname: getLabel('17495', '季度')},
        {key: "3", showname: getLabel('20729', '半年')},
        {key: "4", showname: getLabel('17138', '年度')}
    ];
    @observable statusOption = [
        {key: "", showname: ""},
        {key: "0", showname: getLabel('220', '草稿')},
        {key: "1", showname: getLabel('19134', '审批中')},
        {key: "2", showname: getLabel('236', '退回')},
        {key: "3", showname: getLabel('508866', '已通过')},
    ];
    @observable getType = {
        "1": getLabel('19398', '月度'),
        "2": getLabel('17495', '季度'),
        "3": getLabel('20729', '半年'),
        "4": getLabel('17138', '年度')
    };
    @observable getStatus = {
        "0": getLabel('220', '草稿'),
        "1": getLabel('19134', '审批中'),
        "2": getLabel('236', '退回'),
        "3": getLabel('508866', '已通过'),
    };
    @observable programStatus = {//方案状态
        "": getLabel('15808', '未设置'),
        "0": getLabel('220', '草稿'),
        "1": getLabel('19134', '审批中'),
        "2": getLabel('236', '退回'),
        "3": getLabel('508866', '已通过'),
        "4": getLabel('15808', '未设置'),
        "13": getLabel('384564', '已禁用')
    };
    colorType = {//颜色类型
        '': '#D81D19',
        0: '#ACA207',
        1: '#868686',
        2: '#B916E8',
        3: '#49D732',
        4: '#D81D19',
        13: '#868686',
    };

    @observable form = { //表单
        groupid: '', //考核组id
        programid: '', //方案id
        programtype: '', //考核周期类型（年度、半年、季度、月度）
        resourceid: "", //被考核人id
        startdate: '', //生效日期
        operation: '', //操作类型
        remark: '', //考核说明
        auditids: '', //考核审批人
        auditnames: '', //考核审核人名称
        assessDetailData: [], //考核明细数据
        accessScoreData: [], //考核评分数据
    }

    @observable quoteParams = { //引用方案指标查询参数
        type: '', //0引用方案或指标/1查询指标方案
        templateid: '', //方案id
        programid: '', //方案id
        programname: '', //名称
        programtype: null, //类型
        status: null, //状态
        pageSize: 10, //每页显示数量
        current: 1, //当前页数
    }

    @observable detail = { //当前操作权限
        titlename: '', //标题
        managerid: '', //被考核人上级id
        managername: '', //被考核人上级名称
        managerid2: '', //被考核人上级的上级id
        managername2: '', //被考核人上级的上级名称
        programstatus: null, //方案状态
        waitAuditName: '', //审核状态待审核人
        noprogram: true, //没有项目标记
        noticeMessage: "", //方案提示生效信息
        noticeDate: "", //方案提示生效日期最大值
        nomsg: '', //方案提示语
        manager: false, //是否主管
        canedit: false, //是否能编辑
        canAdd: false, //是否能新建
        canaudit: false, //是否能审批
        canquoteindex: false, //是否能引用指标
        canResetScore: false, //是否能重置评分
        candelete: false,
        stabList: [], //tab数组
        accessItemList: [], //考核指标项列表
    }
    @observable a_remark = "";

    @action("初始化操作")
    doInit = () => {
        this.msg = '';
        this.loading = true;
        this.hasRight = true;
        this.hasCycle = true;
        this.isChangeStartdate = false;
        this.programDetail();
    }

    @action('项目id改变')
    changeProgramId = (id, groupid) => {
        this.form.programid = id;
        this.form.groupid = groupid;
        this.programDetail();
    }

    @action('项目详情')
    programDetail = () => {
        this.loading = true;
        let params = {
            backSetting: this.backSetting,
            programid: this.form.programid,
            groupid: this.form.groupid,
            resourceid: this.form.resourceid,
            programtype: this.form.programtype
        }
        API.programDetailApi(params).then(res => {
            if (res.api_status) {
                this.hasRight = res.hasRight;
                this.hasCycle = res.hasCycle;
                this.backProgram = res.backProgram;
                this.msg = '1';//有数据
                this.detail.canResetScore = res.canResetScore;
                this.form.programid = res.programid;
                this.form.programtype = res.programtype;
                this.form.resourceid = res.resourceid;
                this.form.startdate = res.startdate;
                this.form.remark = res.remark;
                this.a_remark = res.remark;
                this.form.auditids = res.auditids || '';
                this.form.auditnames = res.auditnames || '';
                this.form.assessDetailData = res.detail || [];
                this.form.accessScoreData = res.score || [];
                this.detail.managerid = res.managerid;
                this.detail.managername = res.managername;
                this.detail.managerid2 = res.managerid2;
                this.detail.managername2 = res.managername2;
                this.detail.titlename = res.titlename;
                this.detail.programstatus = res.programstatus;
                this.detail.nomsg = res.nomsg;
                this.detail.noprogram = res.noprogram;
                this.detail.noticeDate = res.noticeDate;
                this.detail.noticeMessage = res.noticeMessage;
                this.detail.accessItemList = res.accessItemList || [];
                this.detail.canedit = res.canedit;
                this.detail.candelete = res.candelete;
                this.detail.canAdd = res.canAdd;
                this.detail.canquoteindex = res.canquoteindex;
                this.detail.canaudit = res.canaudit;
                this.detail.waitAuditName = res.waitAuditName;
                this.detail.stabList = res.stabList;
                this.otherProgram = res.otherProgram;
                this.auditidsManager = res.auditidsManager || false;

                this.addStatus = false;
                //获取操作日志
                this.logList = [];
                this.getLogList();
            } else {
                message.error(res.msg || getLabel('508818', '接口调用失败！'))
            }
            this.loading = false;
        })
    }

    @action("搜索条件改变")
    onFormChange = (params) => {
        for (let key in params) {
            this.form[key] = params[key];
        }
    }

    @action("操作数据")
    operation = (operation, updateNum) => {
        if (this.backSetting && this.addStatus) {
            this.form.resourceid = null
        }
        this.form = {
            ...this.form,
            backSetting: this.backSetting,//是否后台设置
            operation: operation
        }
        this.loading = true;
        this.isChangeStartdate = false
        if (operation != "delete") {
            if (this.addStatus) {
                this.form.programid = null;
            }
            //this.form.assessDetailData = JSON.stringify(this.form.assessDetailData);
            this.form.accessScoreData.map(item => {
                if (item.checkuserid == this.detail.managerid && item.checkusername.includes(getLabel('15709', '直接上级'))) {
                    item.checkuserid = '-1'
                }
            });
            //this.form.accessScoreData = JSON.stringify(this.form.accessScoreData);
            if (this.backSetting) {
                if (this.auditidsManager) {
                    if (this.form.auditids) {
                        this.form.auditids = this.form.auditids + ',-1';
                    } else {
                        this.form.auditids = '-1';
                    }
                }
            } else {
                //若考核审批的审核人是上级的上级，则替换审核人id为-1
                if (this.form.auditnames && this.form.auditnames.includes(getLabel('508574', '上级的上级'))) {
                    let ids = this.form.auditids.split(",");
                    let newids = '';
                    ids.forEach(id=> {
                        if (id == this.detail.managerid2) {
                            newids = newids + ",-1";
                        } else {
                            newids = newids + "," + id;
                        }
                    })
                    this.form.auditids = newids.substring(1)
                }
            }
        }
        let params = {...this.form};
        params.accessScoreData = JSON.stringify(this.form.accessScoreData);
        params.assessDetailData = JSON.stringify(this.form.assessDetailData);
        API.programOperationApi(params).then((res) => {
            if (res.api_status) {
                message.success(getLabel('30700', '操作成功'));
                if ((operation == 'save' || operation == 'submit') && this.addStatus) {
                    this.form.programid = res.programid;
                }
                if (operation == 'delete') {
                    this.form.programid = null;
                }
                this.programDetail();
                if (window.opener && typeof window.opener.RefreshProgramList == 'function') {
                    window.opener.RefreshProgramList();
                }
                if (typeof updateNum == 'function') {
                    updateNum();
                }
            } else {
                message.error(res.msg || getLabel('508818', '接口调用失败！'))
            }
            this.loading = false;
        })
    }

    @action("操作引用指标方案")
    operationQuote = (operation, quoteid, updateNum) => {
        if (this.addStatus) {
            this.form.programid = null;
        }
        let params = {
            operation: operation,
            quoteid: quoteid,
            programid: this.form.programid,
            programtype: this.form.programtype,
            resourceid: this.form.resourceid,
        };
        this.loading = true;
        API.programOperationApi(params).then(res => {
            if (res.api_status) {
                message.success(getLabel('30700', '操作成功'));
                this.closeForm();
                if (operation == 'quote' && this.addStatus) {
                    this.form.programid = res.programid;
                }
                this.programDetail();
                //操作成功后，更新列表状态
                if (window.opener && typeof window.opener.RefreshProgramList == 'function') {
                    window.opener.RefreshProgramList();
                }
                if (typeof updateNum == 'function') {
                    updateNum();
                }
            } else {
                message.error(res.msg || getLabel('508818', '接口调用失败！'))
            }
            this.loading = false;
        })
    }

    @action("方案审核-操作")
    programAuditOperation = (params) => {
        this.loading = true;
        programAuditOperationApi(params).then(action(res => {
            if (res.api_status) {
                message.success(getLabel('30700', '操作成功'));
                this.programDetail();
                if (window.opener && typeof window.opener.RefreshProgramAuditList == 'function') {
                    window.opener.RefreshProgramAuditList();
                }
                if (window.opener && typeof window.opener.RefreshProgramList == 'function') {
                    window.opener.RefreshProgramList();
                }
            } else {
                message.error(res.msg || getLabel('508818', '接口调用失败！'))
            }
            this.loading = false;
        }))
    }

    @action("初始化引用指标dialog")
    initQuoteDialog = (flag) => {
        this.showDialog = true;
        this.quoteProgram = flag;
        this.quoteParams.programtype = this.form.programtype;
        if(!this.addStatus){
            this.quoteParams.programid = this.form.programid;
        }
        this.getQuoteListData();
    }

    @action("引用指标方案查询条件变更")
    quoteParamsChange = (val, type) => {
        this.quoteParams.current = 1;
        this.quoteParams[type] = val;
        this.getQuoteListData();
    }

    @action("引用指标方案列表")
    getQuoteListData = () => {
        this.loading = true;
        API.programBrowserApi(this.quoteParams).then(action(res => {
            if (res.api_status) {
                this.data = res.data;
                this.total = res.total;
                this.hasRight = res.hasRight;
                this.loading = false;
            } else {
                message.error(res.msg || getLabel('508818', '接口调用失败！'))
            }
            this.loading = false;
        }))
    };

    @action("关闭引用指标方案dialog")
    closeItemForm = () => {
        this.showItemDialog = false;
        this.quoteParams = {
            type: '',
            templateid: '',
            programid: '', //方案id
            programname: '', //名称
            programtype: null, //类型
            status: null, //状态
            //分页参数
            pageSize: 10, //每页显示数量
            current: 1, //当前页数
        }
    }

    @action("关闭引用指标方案dialog")
    closeForm = () => {
        this.showDialog = false;
        this.quoteParams = {
            type: '',
            templateid: '',
            programid: '', //方案id
            programname: '', //名称
            programtype: null, //类型
            status: null, //状态
            //分页参数
            pageSize: 10, //每页显示数量
            current: 1, //当前页数
        }
    }

    @action("新建")
    doAdd = () => {
        this.loading = false;
        this.msg = 1;
        this.programtype = 1;
        this.addStatus = true;
        this.form = {
            groupid: this.form.groupid,
            programid: this.form.programid, //方案id
            programtype: this.form.programtype, //考核周期类型（年度、半年、季度、月度）
            resourceid: this.form.resourceid, //被考核人id
            startdate: '', //生效日期
            operation: '', //操作类型
            remark: '', //考核说明
            auditids: '', //考核审批人
            auditnames: '', //考核审核人名称
            assessDetailData: [], //考核明细数据
            accessScoreData: [], //考核评分数据
        }
        this.a_remark = "";
        //过滤掉disable的考核指标
        this.detail.accessItemList = this.detail.accessItemList.filter(item => !item.disabled);
    }

    @action("取消新建")
    cancelAdd = () => {
        this.addStatus = false;
        this.programDetail();
    }

    @action("日志列表")
    getLogList = () => {
        if (this.form.programid != undefined && this.form.programid != '') {
            this.loading = true;
            let params = {
                programid: this.form.programid,
                current: this.logCurrent,
                pageSize: this.pageSize,
            };
            API.programLogListApi(params).then(action(res => {
                if (res.api_status) {
                    if (res.data) {
                        this.logList = this.logList.concat(res.data);
                    }
                    this.logTotal = res.total;
                } else {
                    message.error(res.msg || getLabel('508818', '接口调用失败！'))
                }
                this.loading = false;
            }))
        }
    }

}